package py.com.mblj.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import py.com.mblj.domain.Denuncias;
import py.com.mblj.util.HibernateUtil;

/**
 * Main entry point.
 *
 * @author markos
 */
public class davEntryPoint implements EntryPoint {

    private Label lblServerReply = new Label(); //respuesta del servidor
    private Button btnAdd = new Button("Agregar denuncia");
    private Button btnDel = new Button("Eliminar denuncia");
    private Button btnUpd = new Button("Actualizar denuncia");

    /** 
     * Creates a new instance of davEntryPoint
     */
    public davEntryPoint() {
    }

    public static GWTServiceAsync getService() {
        return GWT.create(GWTService.class);
    }

    /** 
     * The entry point method, called automatically by loading a module
     * that declares an implementing class as an entry-point
     */
    public void onModuleLoad() {
        setButton(btnAdd, HibernateUtil.OP_INSERT);
        setButton(btnDel, HibernateUtil.OP_DELETE);
        setButton(btnUpd, HibernateUtil.OP_UPDATE);

        RootPanel.get().add(lblServerReply);
        RootPanel.get().add(btnAdd);
        RootPanel.get().add(btnDel);
        RootPanel.get().add(btnUpd);
    }

    private void setButton(Button btn, final Integer op) {
        // Create an asynchronous callback to handle the result.
        final AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {

            public void onSuccess(Boolean result) {
                if (result) {
                    lblServerReply.setText("Operacion realizada con exito");
                } else {
                    lblServerReply.setText("Ha ocurrido un error!");
                }
            }

            public void onFailure(Throwable caught) {
                lblServerReply.setText("Communication failed");
            }
        };

        // Listen for the button clicks
        btn.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                Denuncias d = new Denuncias();
                getService().guardarDenuncia(d, op, callback);
            }
        });
    }
}
